import cluster from 'cluster';
import process from 'process';
import Api from './request/api.js';
import { log, sleep } from './utils/utils.js';
import YuekeyunTicketClient from './src/YuekeyunTicketClient.js';
import LeyingTicketClient from './src/LeyingTicketClient.js';
import XingyunTicketClient from './src/XingyunTicketClient.js';
import { TicketChannel } from './constant/index.js';
import TaskClient from './src/TaskClient.js';
import HappinessAppClient from './src/HappinessAppClient.js';
import PhoenixTicketClient from './src/PhoenixTicketClient.js';
const API = new Api();

if (cluster.isPrimary) {
  log(`主进程${process.pid}启动 等待进件`);
  cluster.setupPrimary({
    windowsHide: true, // 隐藏窗口
  });

  const workers = {};

  let intervalTimer;
  (async () => {
    function forkTaskWork() {
      // 任务进程
      const worker = cluster.fork({
        PID_KEY: API.getPidKey(),
        CINEMA_CHANNEL: TicketChannel.TASK,
      });
      workers[worker.process.pid] = {
        key: '',
        worker: worker,
        lastCb: Date.now(),
        createTime: Date.now(),
        channel: TicketChannel.TASK,
      };
      worker.on('message', function (msg) {
        if (msg && msg.topic === 'live') {
          workers[msg.pid].lastCb = Date.now();
        }
      });
    }

    // 进程退出
    cluster.on('exit', (worker, code, signal) => {
      if (worker.isDead()) {
        const workerItem = workers[worker.process.pid];
        if (workerItem) {
          log(`影院 ${workerItem.key} 工作进程退出`);
          delete workers[worker.process.pid];

          // 任务进程 需要重启
          if (Number(workerItem.channel) === TicketChannel.TASK) {
            forkTaskWork();
          }
        }
      }
    });

    if (process.env.CLIENT_NAME === 'MC_0001') {
      // 任务进程
      forkTaskWork();
    }
    setInterval(function () {
      const time = Date.now();
      for (const pid in workers) {
        const workItem = workers[pid];
        if (workItem.lastCb + 5000 < time) {
          log('Long running worker ' + pid + ' killed', 'error');
          workItem.worker.kill(0);
        }
      }
    }, 1000);

    // 通知后台上线
    await API.online().catch((e) => {
      log('链接服务器失败: ' + e.message, 'error');
      process.exit(0);
    });
    // 保持后台在线
    intervalTimer = setInterval(function () {
      API.ping().catch((_e) => {});
    }, 5000);

    // 获取需要激活的影院
    while (true) {
      const cinemaList = await API.activeCinemaList();
      for (const cinema of cinemaList) {
        const code = cinema['cinemas_code'];
        const name = cinema['cinema_name'];
        const key = code + '_' + cinema['cinema_id'] + '_' + cinema.account_id;
        const workerItem = Object.values(workers).find((w) => w.key === key);
        if (workerItem && workerItem.createTime > Date.now() - 30000) {
          continue;
        }
        log(`打开工作进程 ${name}[${key}]\n`);
        const worker = cluster.fork({
          CINEMA_CODE: code,
          CINEMA_CHANNEL: cinema.channel,
          CINEMA_ID: cinema.cinema_id,
          CINEMA_ACC_ID: cinema.account_id,
          CINEMA_ACCOUNT: cinema.account,
          CINEMA_PWD: cinema.pwd,
          CINEMA_NAME: name,
          CINEMA_LINKID: cinema.cinema_data.linkid,
          CINEMA_CITYCODE: cinema.cinema_data.cityCode,
          CINEMA_TOKEN: cinema.login_token,
          CINEMA_DATA: JSON.stringify(cinema.cinema_data),
          CINEMA_FORCE_COUPON: cinema.force_coupon,
          CINEMA_COUPON_FEE: cinema.coupon_fee,
          CINEMA_COUPON_NUM: cinema.coupon_num,
          CINEMA_VIP_BALANCE: cinema.vip_balance,
          PID_KEY: API.getPidKey(),
        });
        workers[worker.process.pid] = {
          key,
          worker: worker,
          lastCb: Date.now(),
          createTime: Date.now(),
          channel: cinema.channel,
        };
        worker.on('message', function (msg) {
          if (msg && msg.topic === 'live') {
            workers[msg.pid].lastCb = Date.now();
          }
        });
      }
      await sleep(1000);
    }
  })().catch((e) => {
    clearInterval(intervalTimer);
    // console.error('主程序异常退出!', e.message);
    API.offline();
  });
} else {
  switch (Number(process.env.CINEMA_CHANNEL)) {
    case TicketChannel.PHOENIX:
      YuekeyunTicketClient();
      break;
    case TicketChannel.HAPPINESS:
      HappinessAppClient();
      break;
    case TicketChannel.LEYING:
      LeyingTicketClient();
      break;
    case TicketChannel.XINGYUN:
      XingyunTicketClient();
      break;
    case TicketChannel.PHOENIX_MP:
        // 凤凰小程序
        PhoenixTicketClient();
      break;
    case TicketChannel.TASK:
      TaskClient();
      break;
  }
  // 每1秒报告一次状态
  const intval = setInterval(function report() {
    if (!process || !process.pid) {
      clearInterval(intval);
      return;
    }
    process.send({
      topic: 'live',
      pid: process.pid,
      channel: process.env.CINEMA_CHANNEL,
    });
  }, 1000);
}
